package com.rsy.demo.internal;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

// 指定我们只处理完整的 HTTP 请求（FullHttpRequest）
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final HelloWordService helloWordService;

    public HttpServerHandler(HelloWordService helloWordService) {
        this.helloWordService = helloWordService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        // 1. 打印请求信息（方便调试）
        System.out.println("Received HTTP Request:");
        System.out.println("URI: " + request.uri());
        System.out.println("Method: " + request.method().name());
        // 2. 准备响应内容
        String responseContent = "Hello, Netty!";

        if (request.uri().contains("hello")) {
            HttpMethod method = request.method();
            if (method.equals(HttpMethod.POST)) {
                ByteBuf content = request.content();
                byte[] body = new byte[content.readableBytes()];
                content.readBytes(body);
                System.out.println("接收到的数据：" + new String(body));
                User user = new ObjectMapper().readValue(body, User.class);
                String s = helloWordService.helloWord(user);
                if (s != null) {
                    responseContent += " 接收到数据：【" + s + "】";
                }
            }
        }

        // 将响应内容转换为 Netty 的 ByteBuf
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer(responseContent, StandardCharsets.UTF_8)
        );

        // 3. 设置响应头
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        // 允许跨域（根据需要设置）
        response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");

        // 4. 写入响应并刷新通道
        ctx.writeAndFlush(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 处理异常，打印日志并关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}